package org.song.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.song.exception.myException.CommonException;
import org.song.exception.result.AjaxResult;
import org.song.util.FunctionUtil;
import org.song.util.email.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理类 , springMvc迁居异常处理底层是基于AOP面向切面编程实现的，其实就是通过横切关注点横切到每一个控制层中即可
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Autowired( required = true )
    @Qualifier( value = "emailUtil")
    private EmailUtil emailUtil;

    /**
     * 运行时异常邮件告警
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = {RuntimeException.class} )
    @ResponseBody
    public AjaxResult<Void> runtimeExceptionHandler(HttpServletRequest request , Exception e) {
        logger.error( request.getRequestURL() + "发生运行时异常: " + e.getMessage() );
        emailUtil.sendEasyEmail( "服务器发生RuntimeException" , "URL: " + request.getRequestURL() + "\nip: " + FunctionUtil.getIpAddress(request) + "\n异常信息：" + e.getMessage());
        return AjaxResult.exception();
    }

    /**
     * 异常邮件告警
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = {Exception.class} )
    @ResponseBody
    public AjaxResult<Void> exceptionHandler(HttpServletRequest request , Exception e) {
        logger.error( request.getRequestURL() + "发生异常: " + e.getMessage() );
        emailUtil.sendEasyEmail( "服务器发生Exception" , "URL: " + request.getRequestURL() + "\nip: " + FunctionUtil.getIpAddress(request) + "\n异常信息：" + e.getMessage());
        return AjaxResult.exception();
    }

    /**
     * 自定义异常全局AOP处理无需邮件告警
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler( value = {CommonException.class} )
    @ResponseBody
    public AjaxResult<Void> commonExceptionHandler( HttpServletRequest request , Exception e ) {
        logger.error( request.getRequestURL() + "发生自定义异常: " + e.getMessage() );
        return AjaxResult.exception( e.getMessage() );
    }

}
